package com.dao;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import com.model.Page;

public abstract class BaseDao<T> implements IDao<T> {

	@Autowired
	NamedParameterJdbcTemplate dao;

	private Class<T> requiredType;

	public BaseDao(final Class<T> requiredType) {
		this.requiredType = requiredType;
	}

	@Override
	public int execute(String sql, Map<String, ?> paramMap) {
		return dao.update(sql, paramMap);
	}

	@Override
	public int delete(String sql, Map<String, ?> paramMap) {
		return dao.update(sql, paramMap);
	}

	@Override
	public int update(String sql, Map<String, ?> paramMap) {
		return dao.update(sql, paramMap);
	}

	@Override
	public T get(String sql, Map<String, ?> paramMap) {
		sql = sql.replace(";", "") + " limit 1";
		return dao.queryForObject(sql, paramMap, BeanPropertyRowMapper.newInstance(requiredType));
	}

	@Override
	public List<T> getList(String sql, Map<String, ?> paramMap) {
		RowMapper<T> rowMapper = new BeanPropertyRowMapper<>(requiredType);
		return dao.query(sql,paramMap, rowMapper);
	}

	@Override
	public Page<T> getPagable(String sql, Map<String, ?> paramMap, Long pageNo, Long pageSize) {
		String countSql = sql.replace("*", "count(*)");
		sql = sql.replace(";", "") + " limit " + pageNo * pageSize + "," + pageSize;
		List<T> list = getList(sql, paramMap);
		Long count = dao.queryForObject(countSql, paramMap, Long.class);
		Page<T> result = new Page<>();
		result.setList(list);
		result.setPageNo(pageNo);
		result.setPageSize(pageSize);
		result.setRowsTotal((long) list.size());
		result.setPageTotal(count / pageSize);
		return result;
	}

}
